package controller;

import dao.JobDao;
import dao.SocketLogDao;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@WebServlet("/ws/algorithm/log")
public class AlgorithmLog  extends HttpServlet {
    private SocketLogDao socketLogDao = new SocketLogDao();
    private JobDao historyJob = new JobDao();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String subTaskHash = request.getParameter("subTaskHash");
        boolean isSuccess = true;
        StringBuilder message = new StringBuilder();
        if(subTaskHash!=null) {
        String logFileUri = socketLogDao.getLogFileUriBySubTaskHash(subTaskHash);
                if (!(logFileUri==null||logFileUri.equals(""))) {
                    File file = new File(logFileUri);

                    // 判断文件是否存在
                    if(file.exists()){
                        BufferedReader bufferedReader;
                        if (logFileUri.substring(logFileUri.lastIndexOf(".") + 1, logFileUri.length()).equals("log")) {
                            bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
                        } else {
                            bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"));
                        }
                        String temp = "";

                        // 读取算法日志文件内容
                        while ((temp = bufferedReader.readLine()) != null) {
                            temp = new String(temp.getBytes());
                            message.append(temp + "\r\n");
                        }
                        bufferedReader.close();
                    }else {
                        isSuccess = false;
                        message.append("获取日志文件失败, 系统找不到指定的文件");
                    }
                } else {
                    isSuccess = false;
                    message.append("获取日志文件失败, 日志文件不存在");
                }
           /* }else {
                isSuccess = false;
                message.append("获取日志文件失败, 该任务不存在!");
            }*/
        }else{
            isSuccess = false;
            message.append("获取日志文件失败, 请正确输入参数!");
        }
        JSONObject resultJson = new JSONObject();
        resultJson.put("result", isSuccess);
        resultJson.put("message", message.toString());
        response.getWriter().write(resultJson.toString());

    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
